import 'dart:async';
import 'dart:convert';

import 'package:crypto/crypto.dart';
import 'package:gameplay_flutter/lib_runtime/extension/string_extension/string_validate.dart';

import '../../../lib_basemodel/chat_room/chat/chat_content.dart';
import '../../../lib_basemodel/chat_room/chat/message_data.dart';
import '../../../lib_basemodel/chat_room/chat/show_item.dart';
import '../../../lib_basemodel/chat_room/socket/req_content.dart';
import '../../../lib_basemodel/user/user.dart';
import '../../../lib_baseview/widget/dialogs.dart';
import '../../../lib_rtc/socket/jr_socket.dart';
import '../../../lib_user/user_manager.dart';
import '../../../resource/language/generated/l10n.dart';
import '../interface/room_page_model.dart';
import '../msg/room_msg.dart';
import '../socket/persistent_uuid.dart';
import 'room_chat_handler.dart';
// import 'room_msg/room_msg.dart';

class RoomSocket with JRSocket {
  final String url;

  /// 房间的 channel
  final String channel;
  late RoomPageModel roomModel;

  var _firstConnect = true;

  // RoomCmdMsgHandler? cmdHandler;
  RoomChatMsgHandler? chatHandler;

  RoomSocket(
      {required this.url, required this.channel, required this.roomModel}) {
    attachPageModel(roomModel);
    connect();
  }

  attachPageModel(RoomPageModel model) {
    rmHandlers();

    roomModel = model;
    // cmdHandler = RoomCmdMsgHandler(model);
    chatHandler = RoomChatMsgHandler(model);

    // addHandler(cmdHandler!);
    addHandler(chatHandler!);

    // 房间业务MsgHandler，全都注册
    // RoomManager.instance.plugins
    //     .map((_) => _.createMsgHandler(model))
    //     .forEach((_) => addHandler(_));

    // _loadHistoryMsg();
  }

  @override
  onConnected() {
    if (_firstConnect) {
      // _loadHistoryMsg();
      _firstConnect = false;
    }
  }

  // _loadHistoryMsg() async {
  //   var result = await getHistoryMsg();
  //   roomModel.barrageListModel.msgList = result;
  // }

  @override
  onReconnected() => _reloadData();

  @override
  onRetryMax([String? msg]) {
    roomModel.disposePageAndData();
    showToast((msg?.isNotEmpty ?? false) ? msg! : T.current.check_offline);
  }

  @override
  String get socketUrl => url;

  @override
  String get token => UserManager.instance.token ?? '';

  // Map<String, dynamic>? wsUrl = await buildWSHeader(connType);

  // @override
  // Map<String, dynamic> get socketParams =>await buildWSHeader();
  @override
  Future<Map<String, dynamic>> get socketParams async {
    // ✅ 添加 async
    return await buildWSHeader();
  }

  var _reloadTime = 0;
  void _reloadData() {
    int now = DateTime.now().millisecondsSinceEpoch;
    if ((now - _reloadTime) <= 2 * 1000) return;

    _reloadTime = now;

    /// 更新房间信息

    // RtcApi.instance
    //     .joinChannel(JoinChannelReq()
    //       ..channelId = channel.channelId
    //       ..reconnect = 1)
    //     .then((rsp) {
    //   if (!rsp.isSuccess || rsp.data?.channel == null) return;
    //   roomModel.updateChannel(rsp.data?.channel);
    // });
  }

  Future<List<RoomMsg>> getHistoryMsg() async {
    // 获取历史消息
    var historyMsgList = <RoomMsg>[];

    // ReqContent reqContent =
    //     await sendReqMsg(ReqContent()..type = 'pull_chat_msg');
    // Map<String, String> body = reqContent.body;

    Map<String, String> body = {};

    if (body['list']?.isEmpty ?? true) return historyMsgList;

    var listJson = jsonDecode(body['list']!);

    if (listJson is! List) return historyMsgList;

    RoomMsg msgItem;
    var reversedList = listJson.reversed;
    for (var _ in reversedList) {
      try {
        showToast('msgItem');
        // msgItem = RoomChatMsgHandler.unpackChatMsg(Message.create()
        //   ..mergeFromProto3Json(jsonDecode(_),
        //       typeRegistry: JRSocket.typeRegistry, ignoreUnknownFields: true));
        // historyMsgList.add(msgItem);
      } catch (e) {}
    }
    return historyMsgList;
  }

  static MessageData createChatMsg(List<ShowItem> items) {
    User? currUser = UserManager.instance.currentUser;
    ChatContent chatContent = ChatContent();
    chatContent.senderUser = currUser;
    // chatContent.senderUser = SimpleUser(
    //     id: currUser?.id,
    //     gender: currUser?.gender,
    //     nickname: currUser?.nickname,
    //     avatar: currUser?.avatar,
    //     emUsername: currUser?.emUsername,
    //     onlineStatus: currUser?.onlineStatus,
    //     gsGroupId: currUser?.gsGroupId,
    //     vipLevelIcon: currUser?.icons.smallIcon,
    //     vipLevel: currUser?.vipLevel,
    //     age: currUser?.age,
    //     car: currUser?.car,
    //     days: currUser?.days,
    //     job: currUser?.job,
    //     tags: currUser?.tags);
    // chatContent.showItem.clear();
    // chatContent.showItem.addAll(items);

    MessageData msgData = MessageData()
      // ..scene = Scene.ROOM_TEXT_CHAT
      ..content = 'content';

    return msgData;
  }

  //// 构建 ws 请求头 ======
  Future<Map<String, dynamic>> buildWSHeader() async {
    // 获取当前时间的时间戳（毫秒）
    int currentTimestamp = DateTime.now().millisecondsSinceEpoch;
    // 将时间戳转换为DateTime对象
    DateTime dateTime = DateTime.fromMillisecondsSinceEpoch(currentTimestamp);

    // 格式化日期时间为 年-月-日 时:分:秒 的格式
    String formattedDateTime =
        '${dateTime.year}-${_formatNumber(dateTime.month)}-${_formatNumber(dateTime.day)} ${_formatNumber(dateTime.hour)}:${_formatNumber(dateTime.minute)}:${_formatNumber(dateTime.second)}';

    // String uidStr = LCUserModel.currentUser()?.userId != null
    //     ? '#${LCUserModel.currentUser()!.userId}'
    //     : '';
    print('当前时间戳: $currentTimestamp');
    print('格式化后的日期时间: $formattedDateTime');

    // String? userUserid = UserManager.instance.currentUser?.userId.toString();
    // if (userUserid != null) {
    //   userUserid = '#$userUserid';
    // }
    String? userUserid;
    if (UserManager.instance.currentUser?.userId != null) {
      userUserid = '#${UserManager.instance.currentUser?.userId}}';
    }

    // 获取应用级持久化标识（无需权限）
    String uuidValue = await getUUID();
    String tmpUUIDStr = '$uuidValue${userUserid ?? ''}';

    String uuid = tmpUUIDStr;
    String key = '9zaO2zXrQacQJDzkPxHXu3ysmQuLkb7B';
    String appName = 'PiPi';
    String device = 'Simulator x64';
    String system = 'iOS';
    String timestamp = formattedDateTime;
    String version = '2.9.3';
    // String token = UserManager.instance.currentUser?.token ?? '';
// APP-a0fd5d9f9160444dbe10db9d0e741d65#2060392
    String signStr = '$uuid$key$appName$device$system$timestamp$version';

    String md5Value = signStr.toMd5();

    Map<String, String> map = {
      "system": system,
      "timestamp": timestamp,
      "key": key,
      "appName": appName,
      "device": device,
      "version": version,
      // "token": token,
    };

    if (uuid.isNotEmpty) {
      map['uuid'] = uuid;
    }

    if (md5Value.length > 25) {
      signStr = md5Value.substring(10, 10 + 15);
      map['sign'] = signStr;
    }

    // 1. 生成请求头参数
    // final headers = map;

    // String signStr = '$uuid$key$appName$device$system$timestamp$version$token';
    // print('$TAG  - Sign String: $signStr'); // 添加调试日志
    // String md5Value = getMd5(signStr);
    print('socket <> - md5 value: $md5Value'); // 添加调试日志

    // Uri tmp = Uri.parse('ws://192.168.199.160:17961/ws').replace(
    //   queryParameters: map..removeWhere((k, v) => v.isEmpty),
    // );

    // print('web-socket-->url: $tmp');
    // return tmp;
    return map;
  }

  Future<String> getUUID() async {
    return await PersistentUUID.getCRUUIDString();
  }

  /// 辅助函数，用于格式化数字，确保是两位数
  String _formatNumber(int number) {
    return number.toString().padLeft(2, '0');
  }
}
